// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate


// 云函数入口函数
const pageAppeal = async function (params) {
  const wxContext = cloud.getWXContext()

  let openid = params.openid
  let title = params.title || '\^'
  let pageNO = params.pageNO || 1
  let pageSize = params.pageSize || 10
  let createTime = params.createTime
  let nearby = params.nearby
  let longitude = params.longitude
  let latitude = params.latitude


  // 排序规则
  let sortRule = createTime ? {
    'createTime': -1
  } : {
    'browseCount': -1
  }

  // 查询条件
  let queryRule = {
    title: new db.RegExp({
      regexp: title,
      options: 'i',
    }),
  }
  if(openid){
    Object.assign(queryRule, {_openid: openid})
  }




  // 查询附近
  if (nearby) {
    // 分页查询诉求
    let appealList = await db.collection('appeal')
      .aggregate()
      // 位置信息
      .geoNear({
        distanceField: 'coordinates', // 输出的每个记录中 distance 即是与给定点的距离
        spherical: true,
        near: db.Geo.Point(longitude, latitude),
        maxDistance: 10000,
        minDistance: 0,
      })
      // 匹配项
      .match(queryRule)
      // 排序
      .sort(sortRule)
      // 连表查询 用户信息
      .lookup({
        from: 'user',
        localField: '_openid',
        foreignField: '_openid',
        as: 'userInfo'
      })
      .addFields({
        userInfo: $.arrayElemAt(['$userInfo', 0])
      })

      // 列表查询点赞信息
      .lookup({
        from: 'appealEndorse',
        localField: '_id',
        foreignField: 'appealId',
        as: 'endorses'
      })
      .addFields({
        endorseCount: $.size('$endorses')
      })

      // 列表查询评论信息
      .lookup({
        from: 'appealComment',
        localField: '_id',
        foreignField: 'appealId',
        as: 'comments'
      })
      .addFields({
        commentCount: $.size('$comments')
      })

      // 判断次诉求用户是否点赞
      .addFields({
        isEndorse: $.gt([$.size($.filter({
          input: '$endorses',
          as: 'item',
          cond: $.eq(['$$item._openid', wxContext.OPENID])
        })), 0])
      })

      // 去掉或者重置 一些值
      .project({
        endorses: false,
        comments: false
      })
      .skip((pageNO - 1) * pageSize)
      .limit(pageSize)
      .end()


    return appealList.list
  }


  // 分页查询诉求
  let appealList = await db.collection('appeal')
    .aggregate()
    // 匹配项
    .match(queryRule)
    // 排序
    .sort(sortRule)
    // 连表查询 用户信息
    .lookup({
      from: 'user',
      localField: '_openid',
      foreignField: '_openid',
      as: 'userInfo'
    })
    .addFields({
      userInfo: $.arrayElemAt(['$userInfo', 0])
    })

    // 列表查询点赞信息
    .lookup({
      from: 'appealEndorse',
      localField: '_id',
      foreignField: 'appealId',
      as: 'endorses'
    })
    .addFields({
      endorseCount: $.size('$endorses')
    })

    // 列表查询评论信息
    .lookup({
      from: 'appealComment',
      localField: '_id',
      foreignField: 'appealId',
      as: 'comments'
    })
    .addFields({
      commentCount: $.size('$comments')
    })

    // 判断次诉求用户是否点赞
    .addFields({
      isEndorse: $.gt([$.size($.filter({
        input: '$endorses',
        as: 'item',
        cond: $.eq(['$$item._openid', wxContext.OPENID])
      })), 0])
    })

    // 去掉或者重置 一些值
    .project({
      endorses: false,
      comments: false
    })
    .skip((pageNO - 1) * pageSize)
    .limit(pageSize)
    .end()


  return appealList.list
}

module.exports = pageAppeal